package utils;

public class Test {
    static class ListNode {
   int val;
    ListNode next = null;
    public ListNode(int val) {
      this.val = val;
    }
  }

    public static void main(String[] args) {
        Test test = new Test();

        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        node1.next = node2;
        ListNode node3 = new ListNode(3);
        node2.next = node3;
        ListNode node4 = new ListNode(4);
        node3.next = node4;

        ListNode result = test.removeNthFromEnd(node1, 1);
        while (result!= null){
            System.out.println(result.val);
            result = result.next;
        }
    }

    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @param n int整型
     * @return ListNode类
     */
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        int length = 0;
        ListNode currentNode = head;
        while(currentNode != null){
            length++;
            currentNode = currentNode.next;
        }

        System.out.println("length:" + length);
        int removeIndex = length - n;
        System.out.println("removeIndex :" + removeIndex );
        if(removeIndex == 0){
            head = head.next;
        }else{
            ListNode lastNode = head;
            ListNode indexNode = head;
            removeIndex = removeIndex;
            for(int index = 0; index <= removeIndex; index++){

                if(index == removeIndex - 1){
                    lastNode = indexNode;
                }


                if(removeIndex == index){
                    System.out.println("lastNode:" + lastNode.val + "   indexNode:" + indexNode.val);
                    lastNode.next = indexNode.next;
                }

                indexNode = indexNode.next;
            }
        }

        return head;
    }
}
